#! usr/bin/perl -w
use strict;

### load orderpedfile
sub LOADordf{
	my $filename=$_[0];
	my %f=();
	my @indlist=();

	open(FILE, $filename) or die "cannot open $filename";
	while(my $line=<FILE>)
	{
		chomp($line);
		my($ind,$father ,$mother)=split(/ /,$line);
		push(@indlist,$ind); 

		$f{$ind}{'father'}=$father;
		$f{$ind}{'mother'}=$mother;
	}
	close FILE;
	return(\%f,\@indlist);
}

### load famfile
sub LOADfamf{
	my $filename=$_[0];
	my %f=();
	
	open(FILE, $filename) or die "cannot open $filename";
	while(my $line=<FILE>)
	{
		chomp($line);
		my($ped,$ind,$father,$mother,$sex,$status)=split(/ /,$line);

		$f{$ind}{'ped'}=$ped;
		$f{$ind}{'father'}=$father;
		$f{$ind}{'mother'}=$mother;
		$f{$ind}{'sex'}=$sex;
		$f{$ind}{'status'}=$status;
	}
	close FILE;
	return(\%f);
}

sub create_newtfamfile{
	my($ref_ordf,$ref_famf,$ref_indlist,$dataname)=@_;
	my %ordfile=%$ref_ordf;
	my %famfile=%$ref_famf;
	my @indlist=@$ref_indlist;

	# write newbimfile to impute
	my $newtfamfile="newtfile/".$dataname."_new.tfam";
	open(TFAMFILE,">$newtfamfile") or die "cannot open TFAMFILE: $newtfamfile $!\n";

	foreach my $item (@indlist){
		print TFAMFILE "$famfile{$item}{'ped'}\t$item\t$ordfile{$item}{'father'}\t$ordfile{$item}{'mother'}\t$famfile{$item}{'sex'}\t$famfile{$item}{'status'}\n";
	}

	close(TFAMFILE);
}
####################################################################

sub main(){
	
	# collect arguments
	my $dataname=$ARGV[0];
	my $orderpedfile=$ARGV[1];
	my $famfile=$ARGV[2];

	# load ordered file
	my($ref_ordfile,$ref_indlist)=&LOADordf($orderpedfile);

	# load fam file
	my $ref_famfile=&LOADfamf($famfile);

	# create new_tfamfile
	&create_newtfamfile($ref_ordfile,$ref_famfile,$ref_indlist,$dataname);

exit;
}

main();
